package com.itheima.reggie.controller;

import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.UUID;

@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {
    @Value("${reggie.path}")
    private String imgPath;

    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        log.info(file.toString());
        String originalFilename = file.getOriginalFilename();
        String endName = originalFilename.substring(originalFilename.lastIndexOf("."));
        String newFileName = UUID.randomUUID().toString() + endName;
        File dir = new File(imgPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        try {
            file.transferTo(new File(imgPath + newFileName));
        } catch (IOException e) {
            e.printStackTrace();
            throw new CustomException("文件上传失败");
        }
        return R.success(newFileName);
    }
    @GetMapping("/download")
    public void  downLoad(HttpServletResponse response,String name){
        log.info("回显画面...name={}",name);
        try {
            String fileNamePath=imgPath+name;
            byte[] content = FileCopyUtils.copyToByteArray(new File(fileNamePath));
            response.getOutputStream().write(content);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    @GetMapping("/download2")
    public void  downLoad2(HttpServletResponse response,String name) {
        log.info("回显画面...name={}", name);
        try {
            String fileNamePath = imgPath + name;
            byte[] content = FileCopyUtils.copyToByteArray(new File(fileNamePath));
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(name, "utf-8"));
            response.getOutputStream().write(content);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
